﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using tracker.Models.BLL;
using tracker.Models;
using System.Data;
using tracker.Models.DTO;

namespace tracker.Controllers
{
    public class HandlerGetDistanceInfoController : Controller
    {
       /// <summary>
       /// Get All Alarm Define
       /// </summary>
       /// <returns></returns>
        [CallAjaxFilter]
        public JsonStringResult Index(string distance, string fromtime, string totime, string limit, string start, string snid, string startspeed, string stopminutes, string filterData)
        {

            string result = "";
            string _username = HttpContext.Session[Common.USER].ToString();
            string _language = HttpContext.Session[Common.LANGUAGE].ToString();
            string timezone = HttpContext.Session[Common.TIMEZONE].ToString();
            _language = _language == string.Empty ? "vi" : _language;

            string snids = snid;

            if (fromtime == null || totime == null || limit == null || start == null || snids == null)
            {
                result = "{totalCount:0,data:[{}]}";
            }
            else
            {
                if (ClassCommon.classValidate.isDateTime(fromtime) && ClassCommon.classValidate.isDateTime(totime) && ClassCommon.classValidate.isInt(limit) && ClassCommon.classValidate.isInt(start))
                {
                    List<ENTTrackerName> listTrackerName = new List<ENTTrackerName>();
                    listTrackerName = HandlerSearchTrackerNameController.getListDeviceByUser(_username);

                    if (filterData == null)
                    {
                        if (listTrackerName.Count > 0)
                        {
                            string username = "";
                            foreach (ENTTrackerName item in listTrackerName)
                            {
                                username += item.username + ",";
                            }
                            username = username.Remove(username.LastIndexOf(","));

                            DataTable dtData = DistanceLogBLL.GetAllPartInfoReport(new string[]{"distance",
                                                                                                "Start",
                                                                                                "End",
                                                                                                "snids",
                                                                                                "FromTime",
                                                                                                "ToTime",
                                                                                                "Username",
                                                                                                "StartSpeed"
                                                                                    },
                                                                                    new object[]{distance,
                                                                                                 int.Parse(start),
                                                                                                 int.Parse(start + limit),
                                                                                                 snids,
                                                                                                 ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                                 ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                                 username,
                                                                                                 float.Parse(startspeed)
                                                                                    }).Tables[0];
                            if (dtData.Rows.Count > 0)
                            {
                                List<ENTGetAllPartInfoReport> listPartInfo = new List<ENTGetAllPartInfoReport>();

                                foreach (DataRow item in dtData.Rows)
                                {
                                    ENTGetAllPartInfoReport ent = new ENTGetAllPartInfoReport();
                                    //Alarm Code

                                    ent.EndTime = ClassCommon.gpsExtensionMethod.convertGMTClientTime(DateTime.Parse(item["TimeEnd"].ToString()), timezone).ToString("yyyy-MM-dd hh:mm:ss tt");
                                    ent.DeviceName = item["DeviceName"].ToString();
                                    ent.StartLatLng = item["LatitudeBegin"].ToString() + "," + item["LongitudeBegin"].ToString();
                                    ent.Period = item["TimeMinutes"].ToString();
                                    ent.StartTime = ClassCommon.gpsExtensionMethod.convertGMTClientTime(DateTime.Parse(item["TimeBegin"].ToString()), timezone).ToString("yyyy-MM-dd hh:mm:ss tt");
                                    ent.Distance = string.Format("{0:N2}", float.Parse(item["Journey"].ToString()) / 1000);
                                    ent.EndLatLng = item["LatitudeEnd"].ToString() + "," + item["LongitudeEnd"].ToString();

                                    DataTable dtNext = DistanceLogBLL.GetNextRecords(new string[]{"minuteTime",
                                                                                                  "DeviceKey",
                                                                                                  "ID"
                                                                                    },
                                                                                    new object[]{int.Parse(ent.Period),
                                                                                                 item["DeviceKey"].ToString(),
                                                                                                 double.Parse(item["ID"].ToString())
                                                                                    }).Tables[0];

                                    if (dtNext.Rows.Count > 0)
                                    {
                                        listPartInfo.Add(ent);
                                    }
                                    dtNext.Dispose();
                                }
                                int iCount = 0;

                                dtData = DistanceLogBLL.GetTotalGetAllPartInfoReport(new string[]{"distance",
                                                                                                "Start",
                                                                                                "End",
                                                                                                "snids",
                                                                                                "FromTime",
                                                                                                "ToTime",
                                                                                                "Username",
                                                                                                "StartSpeed"
                                                                                    },
                                                                                    new object[]{distance,
                                                                                                 int.Parse(start),
                                                                                                 int.Parse(start + limit),
                                                                                                 snids,
                                                                                                 ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(fromtime),timezone),
                                                                                                 ClassCommon.gpsExtensionMethod.convertGMTServerTime(DateTime.Parse(totime),timezone),
                                                                                                 username,
                                                                                                 float.Parse(startspeed)
                                                                                    }).Tables[0];
                                if (dtData.Rows.Count > 0)
                                    iCount = int.Parse(dtData.Rows[0]["Total"].ToString());

                                if (listPartInfo.Count > 0)
                                {
                                    result = Utilities.getJsonString(listPartInfo, "totalCount:" + iCount.ToString() + ",data:", 1);
                                }
                                else
                                {
                                    result = "{totalCount:0,data:[{}]}";
                                }
                            }
                            else
                            {
                                result = "{totalCount:0,data:[{}]}";
                            }
                        }
                        else
                        {
                            result = "{totalCount:0,data:[{}]}";
                        }
                    }
                }
                else
                {
                    result = "{totalCount:0,data:[{}]}";
                }
            }
            return new JsonStringResult(result);
        }
    }
}
